package com.zjl.学习.第06章_块步骤_读操作写.A_ItemReader块读;

import com.zjl.学习.第06章_块步骤_读操作写.User;
import org.springframework.batch.item.file.builder.FlatFileItemReaderBuilder;
import org.springframework.batch.item.file.mapping.FieldSetMapper;
import org.springframework.batch.item.file.transform.FieldSet;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Component;
import org.springframework.validation.BindException;

/**
 * ClassName: A2读平面文件_字段映射
 * Package: com.zjl.学习.第06章_块步骤_读操作写
 * Description:
 *
 * @Author 张蛟龙
 * @Create 2024/8/3 17:42
 * @Version 1.0
 */
public class A2_读平面文件_字段映射 {
    public static void main(String[] args) {
        new FlatFileItemReaderBuilder<User>()
                .name("userMapperItemReader")
                .resource(new ClassPathResource("item/user2.txt"))
                .delimited().delimiter("#")
                .names("id", "name", "age", "province", "city", "area")
                .fieldSetMapper(new MyFieldSetMapper())
                .build();
    }

}
/**
 * 2.FieldSetMapper–字段映射
 *
 */
@Component
class MyFieldSetMapper implements FieldSetMapper<User> {
    @Override
    public User mapFieldSet(FieldSet fieldSet)throws BindException {

        //自己定义映射逻辑
        User User = new User();
        User.setId(fieldSet.readLong("id"));
        User.setAge(fieldSet.readInt("age"));
        User.setName(fieldSet.readString("name"));
        String address = fieldSet.readString("province") + "/"
                + fieldSet.readString("city") + "/" + fieldSet.readString("area");
        User.setAddress(address);
        return User;
    }
}
